package com.specialtreasure.freightdepot.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.core.config.Constants;
import com.app.core.config.HttpApi;
import com.app.core.fragment.BaseNewFragment;
import com.app.core.util.KumaToast;
import com.app.core.util.ScreenUtils;
import com.app.core.util.UserUtils;
import com.app.core.view.LazyViewPager;
import com.app.core.view.MarqueeTextView;
import com.astuetz.PagerSlidingTabStripLazy;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.activity.AddCarActivity;
import com.specialtreasure.freightdepot.activity.MapActivity;
import com.specialtreasure.freightdepot.adapter.InformationPageAdapter;
import com.specialtreasure.freightdepot.mq.MQUtils;
import com.yanzhenjie.httpmodule.http.CallServer;
import com.yanzhenjie.httpmodule.http.Result;
import com.yanzhenjie.httpmodule.http.StringRequest;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.CacheMode;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/8/7 0007.
 * 共享车队页面
 */

public class ShareCarFragment extends BaseNewFragment implements View.OnClickListener {

    public static final String TAG = "ShareCarFragment";
    //    private ShareMotorCadeFragment shareMotorCadeFragment = new ShareMotorCadeFragment();//3个条件
    private TextView tv_title;
    private PagerSlidingTabStripLazy psts_tabs;
    private LazyViewPager vp_pager;
    private MeMotorCadeFragment motorCadeFragment = new MeMotorCadeFragment(); //4个条件
    private NearMotorCadeFragment nearMotorCadeFragment = new NearMotorCadeFragment();//3个条件

    private List<Fragment> infos = new ArrayList<Fragment>();
    private InformationPageAdapter informationPageAdapter;
    private MarqueeTextView tv_navigation;
    private TextView tv_sure;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(mContext, R.layout.frag_share_car, null);
        initView(view);
        return view;
    }


    private void initView(View view) {
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        psts_tabs = (PagerSlidingTabStripLazy) view.findViewById(R.id.psts_tabs);
        vp_pager = (LazyViewPager) view.findViewById(R.id.vp_pager);


        vp_pager.setOnClickListener(this);
        tv_navigation = (MarqueeTextView) view.findViewById(R.id.tv_navigation);
        tv_navigation.setOnClickListener(this);
        view.findViewById(R.id.iv_addcar).setOnClickListener(this);
        view.findViewById(R.id.iv_map).setOnClickListener(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setData();
        getAD();
        initMQ();
    }

    private void initMQ() {
        String bk = "z.505.2." + UserUtils.getUserId() + ".#";
        MQUtils.createQueue(mContext
                , Constants.MQ.MQ_QNAME_EMPTY
                , bk
                , Constants.EventTag.ON_UPDATE_EMPTY
        );
    }

    private void setData() {
        tv_title.setText("车库");
//        show(tv_sure);
//        tv_sure.setText("添加车辆");


        //初始化数据
        //infos.add(shareMotorCadeFragment);
        infos.add(motorCadeFragment);
        infos.add(nearMotorCadeFragment);
        informationPageAdapter = new InformationPageAdapter(getChildFragmentManager());
        //设置fragment
        informationPageAdapter.setInfos(infos);
        //设置导航文本
        String[] TITLES = {"我的车队", "附近车辆"};
        informationPageAdapter.setTITLES(TITLES);
        setTabsValue();
        vp_pager.setAdapter(informationPageAdapter);
        psts_tabs.setViewPager(vp_pager);
//        vp_pager.setOffscreenPageLimit(2);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_map://地图
                AndPermission.with(this)
                        .permission(Permission.LOCATION, Permission.STORAGE) // 多个权限组。
                        .requestCode(300)
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> list) {
                                // TODO do something...
                                if (requestCode == 300) {
//                            AndPermission.defaultSettingDialog(MainActivity.this, 400).show();
                                    MapActivity.open(getActivity());
                                }
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> list) {
                                // TODO 用户没有同意授权，一般弹出Dialog让用户去Setting中授权。
                                if (requestCode == 300) {
                                    KumaToast.show(mContext, "打开");
                                }
                            }
                        })
                        .start();
                break;
            case R.id.iv_addcar://添加车辆
                intent.setClass(mContext, AddCarActivity.class);
                startActivity(intent);
                break;
        }
    }


    @Override
    protected String getFragmentName() {
        return TAG;
    }

    /**
     * 对PagerSlidingTabStrip的各项属性进行赋值。
     */
    private void setTabsValue() {
        // 设置Tab是自动填充满屏幕的
        psts_tabs.setShouldExpand(true);
        // 设置Tab的分割线是透明的
        psts_tabs.setDividerColor(Color.TRANSPARENT);
        // 设置Tab底部线的高度
        psts_tabs.setUnderlineHeight(ScreenUtils.dpToPx(mContext, 1));
        // 设置Tab Indicator的高度
        psts_tabs.setIndicatorHeight(ScreenUtils.dpToPx(mContext, 4));
        // 设置Tab标题文字的大小
        psts_tabs.setTextSize(ScreenUtils.dpToPx(mContext, 16));
        // 设置Tab标题默认的颜色
        psts_tabs.setTextColor(getResources().getColor(R.color.common_474747));
        // 设置选中Tab标题的颜色
        psts_tabs.setSelectedTextColor(getResources().getColor(R.color.common_474747));
        // 设置Tab底部线的颜色
        psts_tabs.setUnderlineColor(getResources().getColor(R.color.common_BDBDB));
        // 设置Tab Indicator的颜色
        psts_tabs.setIndicatorColor(getResources().getColor(R.color.common_FFA57D));
        // 取消点击Tab时的背景色
        psts_tabs.setTabBackground(getResources().getColor(R.color.transparent));
    }


    /**
     * 获取广告
     */
    private void getAD() {
        String url = Constants.HTTP_URL + HttpApi.ADVERTLIST;
        StringRequest request = new StringRequest(url, RequestMethod.POST);

        request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);

        CallServer.getInstance().request(Constants.ONE, request, new SimpleResponseListener<Result<String>>() {
            @Override
            public void onSucceed(int what, Response<Result<String>> response) {
                super.onSucceed(what, response);
                closeDialog();

                String result = response.get().getResult();
                Logger.e("请求成功：" + result);

                JSONObject jsonObject = JSON.parseObject(result);
                if (jsonObject != null) {
                    Integer status = jsonObject.getInteger("status");
                    String msg = jsonObject.getString("msg");

                    if (status != null && status == 0) {
                        List<String> data = JSON.parseArray(jsonObject.getJSONArray("data").toString(), String.class);
                        if (data != null && data.size() > 0) {
                            tv_navigation.init(data);
                        }

                    } else {
                        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();

                    }

                }

            }


        });
    }
}
